package com.hxht.cmp.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * @author alice on 2017/5/27 0027
 */
public class ApplicationContextHelper implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    /**
     * 获取ApplicationContext
     *
     * @return ApplicationContext
     * @author
     */
    public static ApplicationContext getApplicationContext() {
        return context;
    }

    /**
     * @param beanName bean的名字
     * @return 返回一个bean对象
     * @author
     */
    public static Object getBeanById(String beanName) {
        return context.getBean(beanName);
    }

    /**
     * 根据bean的class来查找对象
     * @param clazz
     * @return Object
     */
    @SuppressWarnings("unchecked")
    public static Object getBeanByClass(Class clazz) {
        return context.getBean(clazz);
    }

    /**
     * 根据bean的class来查找所有的对象(包括子类)
     *
     * @param c
     * @return
     */
    public static Map getBeansByClass(Class c) {
        return context.getBeansOfType(c);
    }
}
